package util;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by WF on 2020/10/24 10:39
 */
@Data
@ConfigurationProperties("jwt.config")
@Component
public class JwtUtil {
    private String key;         //加密key
    private long ttl;           //过期时间

    //1.创建jwt
    public String createJWT(String id, String subject, String roles) {
        System.out.println(key + "," + ttl);
        //1.1)得到系统时间的毫秒值
        long timeMillis = System.currentTimeMillis();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuedAt(new Date())
                .claim("roles",roles)
                .signWith(SignatureAlgorithm.HS256, key);
        //1.2)设置过期时间
        if(ttl > 0){
            jwtBuilder.setExpiration(new Date(timeMillis + ttl));
        }
        //1.3)返回得到的token
        return jwtBuilder.compact();
    }

    //2.解析jwt
    public Claims parseJWT(String token){

        try {
            return  Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
        } catch (MalformedJwtException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            System.out.println("token串不正确！");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return null;
    }

}
